package sanshi.contect.udpstarter.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sanshi.contect.udpstarter.entity.UDPEntity;
import sanshi.contect.udpstarter.handler.ProductMsgHandler;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * udp服务端
 */
@Slf4j
@Component
public class UDPServer {

    private static final String OVERMARK = "over";

    @Autowired
    private UDPEntity entity;

    @Autowired
    private ProductMsgHandler productMsgHandler;
    

    /**
     * 发送数据接口
     */
    public void start() {

        DatagramSocket socket = null;
        try {
            //常见监听
            socket = new DatagramSocket(entity.getServerPort());

            ByteBuffer byteBuffer = ByteBuffer.allocate(entity.getBufferSize());
            for (;;) {
                //缓冲区(直接内存，非JVM内存)
                //准备接收数据的容器
                byte[] data = new byte[entity.getByteSize()];
                DatagramPacket packet = new DatagramPacket(data, data.length);

                //接收客户端发送的数据
                // 此方法在接收到数据报之前会一直阻塞
                socket.receive(packet);
                //获取到数据
                byte[] bytes = packet.getData();
                //检查是否是否发送完成
                if (!checkOver(new String(bytes))) {
                    byteBuffer.put(bytes);
                } else {
                    // 接收数据，做后续的处理
                    new Thread(() -> {
                        byte[] result = byteBuffer.array();
                        byteBuffer.clear();
                        log.info("===========================>数据接收完成<===========================");
                        productMsgHandler.saveMsg(result);
                    }).start();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 判断数据是否发送完毕
     * @param msg 接收的数据
     * @return true 接收完成  false 还在接收数据
     */
    public static boolean checkOver(String msg) {
        return OVERMARK.trim().equals(msg.trim());
    }


}
